package com.vfa.test;

import java.util.ArrayList;

import com.vfa.data.SettingActivity;
import com.vfa.vocaburay.R;
import com.vfa.vocaburay.vfaMain;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.Toast;

public class InsertQuestion extends Activity{
	//dialog
	private static final int DIALOG_NEW_CATAGORY = 2;
	private static final int DIALOG_NEW_QUESTION = 0;
	private static final int DIALOG_DELETE_ANSWER = 1;
	//menu
	private static final String SETTING = "Settings";
	private static final String LEVELMANAGE = "Level Manage";
	
	//goi cac class
	private DynamicQuestionItem itemanswer;
	QuestionData questiondata;
	private ArrayList<AnswerE> arraylistAnswer;
	
	private int layoutnum, rightanswerindex, riwro;
	private EditText etquestion;
	private String question;
	private String dialogmessage;
	// cac widget
	LinearLayout insertlayout, layoutitem;
	private Button btnInsertAndUpdateAnswer, btnNewLevel;
	private ImageView imgMinus, imgAdd;
	private Spinner spinner_Level;
	
	//get to update
	private int getidupdate =0;
	private Bundle getbundle;
	private int questionid;
	private String rightanswer="", temp;
	//private int answerid;
	private String[] answer;
	private int[] answerid;
	
	public static DynamicQuestionItem rightItem = null;
	
	public static int positiveitem = -1;;
	private int deletepostion;
	
	private ArrayAdapter<String> cataadapter;
	private ArrayList<CatagoryE> arraylistcatagory;
	private ArrayList<String> arrlistcata;
	private CatagoryE cataitem;
	private String catagoryname;
	private String catagorynameinquestion;
	
	
	//get SharePre
	private int numanswer;
	//priva
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.insertquestionlayout);
		
		imgAdd = (ImageView)findViewById(R.id.img_btnAdd);
		btnInsertAndUpdateAnswer = (Button)findViewById(R.id.btnInsertAndUpdateAnswer);
		btnNewLevel = (Button)findViewById(R.id.btn_NewLevel);
		spinner_Level = (Spinner)findViewById(R.id.spinner_levelquestion);
		etquestion = (EditText)findViewById(R.id.editText_QuestionInserted);
		imgMinus = (ImageView)findViewById(R.id.img_Minus);
		
		
		insertlayout = (LinearLayout)findViewById(R.id.linearLayout_InsertAnswer);
		insertlayout.addView(new DynamicQuestionItem(this,1));
		
		arraylistcatagory = new ArrayList<CatagoryE>();
		arrlistcata = new ArrayList<String>();
		
		
		getbundle  = getIntent().getExtras();
		if(getbundle.getInt("flagbundle")==2)
		{
			getidupdate=getbundle.getInt("idquestion");
			getIdQuestionToUpdate();
		}
		
		imgAdd.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				AddNewAnswer();
			}
		});
		
		showLevel();
		questiondata = new QuestionData(this);
		btnNewLevel.setOnClickListener(btn_addNewCatagory);
		
		LoadSharePreferences();
		
		spinner_Level.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
			
			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				//catagoryname = (String) spinner_Level.getItemAtPosition(arg2);
				if (catagorynameinquestion!=null) {
						catagoryname = catagorynameinquestion;
						for(int i=0;i<arraylistcatagory.size();i++)	{
							if(spinner_Level.getItemAtPosition(i).toString().equals(catagorynameinquestion)){
								spinner_Level.setSelection(i);
								System.out.println("spinner_Level.setSelection(i);  "+i);
							}
						}
				} else {
						catagoryname = spinner_Level.getSelectedItem().toString();
						}
					
//					}else{
//						spinner_Level.setSelection(0);
//						}
				System.out.println("catagoryname  = = "+catagoryname );
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				// TODO Auto-generated method stub
				
			}
		});
		
	}
	
	private void LoadSharePreferences(){
		SharedPreferences sharedPreferences = getSharedPreferences("InsertQuestion", MODE_PRIVATE);
		numanswer = sharedPreferences.getInt(SettingActivity.NUMANSWER, 1);
		layoutnum = insertlayout.getChildCount();
		for (int i = layoutnum; i < numanswer; i++) {
			AddNewAnswer();
		}
		catagoryname = sharedPreferences.getString(SettingActivity.CATA, spinner_Level.getSelectedItem().toString());
		
		System.out.println("catagory get from sharepre  =  "+ catagoryname);
		
		for(int i=0;i<arraylistcatagory.size();i++)	{
			if(spinner_Level.getItemAtPosition(i).toString().equals(catagoryname)){
				spinner_Level.setSelection(i);
				System.out.println("spinner_Level.setSelection(i);  "+i);
			}
		}
	}
	
	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		super.onStop();
//		DataHelperTest dataHelperTest = null;
//		dataHelperTest.CloseData();
	}
	
	@Override
	protected void onRestart() {
		// TODO Auto-generated method stub
		super.onRestart();
		
		LoadSharePreferences();
		
	}
	private void showLevel(){
		getCatagory();
		spinner_Level.setAdapter(cataadapter);
		
	}
	
	private android.view.View.OnClickListener btn_addNewCatagory = new android.view.View.OnClickListener() {
		
		@Override
		public void onClick(View v) {
			showDialog(DIALOG_NEW_CATAGORY);
		}
	};
	
	private void getCatagory(){
		
		arraylistcatagory = questiondata.getAllCatagory();
		for (int i = 0; i < arraylistcatagory.size(); i++) {
			cataitem = arraylistcatagory.get(i);
			String level = cataitem.getCatagoryName();
			
			arrlistcata.add(level);
		}
		
		cataadapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, arrlistcata);
		cataadapter.notifyDataSetChanged();
		cataadapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		System.out.println(cataadapter.getCount());
	}
	
	
	public void getIdQuestionToUpdate(){
		if(getidupdate !=0){
			questionid = getidupdate;
			question=getbundle.getString("question");
			rightanswer = getbundle.getString("ranswer");
			btnInsertAndUpdateAnswer.setText("Update");
			
			returnAnswerarr(questionid);
			catagorynameinquestion = questiondata.getCatabyQuestionid(questionid);
			System.out.println(catagorynameinquestion);
			etquestion.setText(question);
			
		}
	}
	
	
	public void returnAnswerarr(int idquestion){
		arraylistAnswer  = questiondata.getAnswer(idquestion);
		answer = new String[arraylistAnswer.size()];
		answerid = new int[arraylistAnswer.size()];
		
		
		for(int i=0;i<arraylistAnswer.size();i++){
			answer[i] = arraylistAnswer.get(i).getAnswer();
			answerid[i] = arraylistAnswer.get(i).getAnswerid();
			
			if(answer[i].equals(rightanswer))
			{
				rightanswerindex = i;
			}
		}
		
		for(int i=0;i<answer.length;i++){
			itemanswer = (DynamicQuestionItem)insertlayout.getChildAt(i);
			if(i==0)
			{
				itemanswer.setEditText(answer[i]);
			}
			if(i>0){
				insertlayout.addView(new DynamicQuestionItem(this,i+1));
				itemanswer = (DynamicQuestionItem)insertlayout.getChildAt(i);
				itemanswer.setEditText(answer[i]);
				itemanswer.setposition(i);
				}
			
			if(rightanswerindex ==i){
				itemanswer.raditem.setChecked(true);
			}
		}
		addImageId();
		
	}
	
	
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		
		layoutnum = insertlayout.getChildCount();
//		System.out.println("layoutnum ===   " + layoutnum);
//		if(layoutnum==1){
//			itemanswer.setImageResource(R.drawable.btn_sub_touch);
//		}
	}
	
	public void AddNewAnswer(){
		layoutnum = insertlayout.getChildCount();
		insertlayout.addView(new DynamicQuestionItem(this,layoutnum+1));
		layoutnum = insertlayout.getChildCount();
		
		for(int i=0; i<layoutnum;i++)
		{
			itemanswer = (DynamicQuestionItem)insertlayout.getChildAt(i);
			itemanswer.setposition(i);

		}
		addImageId();
		
		System.out.println("layoutnum ===   " + layoutnum);
	}
	public void addImageId(){
		layoutnum = insertlayout.getChildCount();
		System.out.println( "layout num kiem tra =  "+layoutnum);
		for(int i=0; i<layoutnum;i++)
		{
			itemanswer = (DynamicQuestionItem)insertlayout.getChildAt(i);
			if(layoutnum==1)
			{
				itemanswer.setImageResource(R.drawable.btn_sub_touch);
			}
			else {
				itemanswer.setImageResource(R.drawable.btn_sub);
			}
		}
	}
	public void onClick_imgMinus(int position){
		this.deletepostion = position;
		showDialog(DIALOG_DELETE_ANSWER);
		
		
	}
	// sua lai get right
	public void getrightAnswer(){
		for(int i=0;i<layoutnum;i++){
			itemanswer = (DynamicQuestionItem)insertlayout.getChildAt(i);
			//System.out.println(itemanswer.raditem.isChecked());
			if(itemanswer.raditem.isChecked()){
				rightanswer = itemanswer.getEditText().toString();
				System.out.println("vi tri ========= "+i);
				break;
			}
			else{
				rightanswer="";
			}
			
		}
		System.out.println("right answer == "+rightanswer);
	}
	
	public Boolean checkRightAnswer(){
		getrightAnswer();
		
		if(rightanswer.length()<1||rightanswer.equals("")){
			return false;
		}
		else return true;
	}
	public Boolean checkAnswer(){
		layoutnum = insertlayout.getChildCount();
		String stranswer;
		for(int i=0;i<layoutnum;i++)
		{
			itemanswer = (DynamicQuestionItem)insertlayout.getChildAt(i);
			stranswer = itemanswer.getEditText();
			if(stranswer.length()==0 || stranswer.equals("")){
				return false;
			}
			
		}
		return true;
			
	}
	
	public void GetInsertQAA(View v){
		question = String.valueOf(etquestion.getText());
		layoutnum = insertlayout.getChildCount();
		
		questiondata = new QuestionData(this);
		
		if(checkAnswer()){
			if(btnInsertAndUpdateAnswer.getText().equals("Insert")){
				System.out.println("kiem tra answer = "+checkAnswer());
				InsertQuestion();
			}		
			
			if(btnInsertAndUpdateAnswer.getText().equals("Update")){
				
				System.out.println("kiem tra answer = "+checkAnswer());
				UpdateQuestion();
			}
		}
		else {
			dialogmessage = "Please check your answer! ";
			showDialog(DIALOG_NEW_QUESTION);
		}
	}
	
	
	private void InsertQuestion(){
		if(question.length()<=0){
			dialogmessage = "You must fill full information";
			showDialog(DIALOG_NEW_QUESTION);
		}
		else{
			if(checkRightAnswer()){
				try{
				question = question.replaceAll("[']", "''");
				//System.out.println(question);
					questiondata = new QuestionData(this);
					questiondata.InsertQuestion(question);
					//System.out.println("insert Q");
					questiondata.returnIdQuestion(question);
					
					//System.out.println("catagoryname = " + catagoryname);
					//System.out.println("idquestion = " + questionid);
					questiondata.InsertQuestionInCata(catagoryname);
					//System.out.println("return Q");
					
					for(int i=0;i<layoutnum;i++){
						itemanswer = (DynamicQuestionItem)insertlayout.getChildAt(i);

						if(itemanswer.raditem.isChecked())
								riwro=1;
						else
							riwro=0;
						
						questiondata.InsertAnswer(itemanswer.getEditText(), riwro);	
					}
					
					Toast.makeText(getApplicationContext(), "Inserted", Toast.LENGTH_SHORT).show();
					ClearWidget();
				} catch (Exception e) {
					System.out.println("Error while inser question");
				}
				
			}
			else{
				dialogmessage = "Please fill the right answer again!";
				showDialog(DIALOG_NEW_QUESTION);
			}
			
		}
	}
	
	private void UpdateQuestion(){
		
		int firstanswernum = answer.length;
		layoutnum = insertlayout.getChildCount();
		
		if(question.length()<=0){
			dialogmessage = "You must fill full information";
			showDialog(DIALOG_NEW_QUESTION);
		}
		else if(checkRightAnswer()){
			question = question.replaceAll("[']", "''");
			questiondata.UpdateQuestion(questionid, question);
			//delete question trong catagory truoc
			questiondata.DeleteQuestionInCata(catagorynameinquestion, questionid);
			//sau do insert vao catagory lua chon
			questiondata.InsertQuestionInCata(catagoryname, questionid);
			
			
			//questiondata.
			if(layoutnum>=firstanswernum){
				
				for(int i=0;i<answer.length;i++){
					
					itemanswer = (DynamicQuestionItem)insertlayout.getChildAt(i);
					if(itemanswer.raditem.isChecked())
						riwro=1;
					else
						riwro=0;
					
					questiondata.UpdateAnswer(answerid[i], itemanswer.getEditText(), riwro);
				}
				if(layoutnum>firstanswernum){
					questiondata.returnIdQuestion(question);
					//System.out.println("fffffffffffffffffffffffffff = = = = == "+(layoutnum>firstanswernum));
					
					for(int i=firstanswernum;i<layoutnum;i++){
						itemanswer = (DynamicQuestionItem)insertlayout.getChildAt(i);
						
						if(itemanswer.raditem.isChecked())
							riwro=1;
						else
							riwro=0;
							
						questiondata.InsertAnswer(itemanswer.getEditText(), riwro);	
					}
					
				}
			}
			
			if(layoutnum<firstanswernum){
				for(int i=0;i<layoutnum;i++){
					itemanswer = (DynamicQuestionItem)insertlayout.getChildAt(i);
					if(itemanswer.raditem.isChecked())
						riwro=1;
					else
						riwro=0;
					
					questiondata.UpdateAnswer(answerid[i], itemanswer.getEditText(), riwro);
				}
				
				for(int i=layoutnum;i<firstanswernum;i++){
					try {
						questiondata.DeleteAnswer(answerid[i]);
					} catch (Exception e) {
						System.out.println("Exception =  "+e);
					}
					
				}
			}
			
			Toast.makeText(getApplicationContext(), "Update successfuly!", Toast.LENGTH_SHORT).show();
			InsertQuestion.this.finish();
		}
		else{
			dialogmessage = "Please fill the right answer again!";
			showDialog(DIALOG_NEW_QUESTION);
		}
		
		
	}
	private void ClearWidget(){
		
		while(layoutnum>1){
			
			System.out.println("so lay out hien tai   ====  "+layoutnum);
			insertlayout.removeViewAt(layoutnum-1);
			
			layoutnum = insertlayout.getChildCount();
		}
		for(int i=0; i<layoutnum;i++)
		{
			itemanswer = (DynamicQuestionItem)insertlayout.getChildAt(i);
			itemanswer.setEditText("");
		}
		itemanswer.setImageResource(R.drawable.btn_sub_touch);
		etquestion.setText("");
		
	}

	@Override
	protected void onPause() {
		super.onPause();
	}
	
	
	
	@Override
	public void onBackPressed() {
		// TODO Auto-generated method stub
		super.onBackPressed();
		
		Intent intent = new Intent(getApplicationContext(), ListQuestion.class);
		startActivity(intent);
		InsertQuestion.this.finish();
	}
	@Override
	protected Dialog onCreateDialog(int id) {
		// TODO Auto-generated method stub
		//return super.onCreateDialog(id);
		   AlertDialog.Builder dialog =new AlertDialog.Builder(this);
		switch (id) {
		
		case DIALOG_NEW_QUESTION:
			dialog.setTitle(" Notice! ");
			dialog.setMessage(dialogmessage);
			dialog.setPositiveButton("OK", new DialogInterface.OnClickListener() {
				
				@Override
				public void onClick(DialogInterface dialog, int which) {
					dialog.dismiss();
				}
			});
			AlertDialog alertnewquestion = dialog.create();
			return alertnewquestion;
			//alert1.show();
			
			//break;
		case DIALOG_DELETE_ANSWER:
			dialog.setTitle(" Notice! ");
			dialog.setMessage("Do you want to delete this answer ? ");
			dialog.setPositiveButton("OK", new DialogInterface.OnClickListener() {
				
				@Override
				public void onClick(DialogInterface dialog, int which) {
					try {
						insertlayout.removeViewAt(deletepostion);
						System.out.println("remove item att "+ (deletepostion));
					} catch (Exception e) {
						System.out.println("remove item att "+ (deletepostion));
					}
					
					layoutnum = insertlayout.getChildCount();
					for(int i=0; i<layoutnum;i++)
					{
						itemanswer = (DynamicQuestionItem)insertlayout.getChildAt(i);
						itemanswer.setposition(i);
					}
					addImageId();
				}
			});
			
			dialog.setNegativeButton("Cancel", new  DialogInterface.OnClickListener() {
				
				@Override
				public void onClick(DialogInterface dialog, int which) {
					dialog.dismiss();
					
				}
			});
			AlertDialog alertdelitem = dialog.create();
			//alertdelitem.show();
			return alertdelitem;
			//break;
			
		case DIALOG_NEW_CATAGORY:
			 LayoutInflater factory1 = LayoutInflater.from(this);
	            final View textEntryView1 = factory1.inflate(R.layout.inputcategory, null);
	            return new AlertDialog.Builder(InsertQuestion.this)
	                   .setTitle("Input new Catagory")
	                .setView(textEntryView1)
	                .setPositiveButton("Add", new DialogInterface.OnClickListener() {
	                    public void onClick(DialogInterface dialog, int whichButton) {
	                    	final EditText etNewCategory = (EditText) textEntryView1.findViewById(R.id.etNewCategory);
	                    	String strNewCatagory =  String.valueOf(etNewCategory.getText()).trim();
	                        // them catalog
	                    	if(!strNewCatagory.equals("") || strNewCatagory.length() >0){
	                    		try {
	                    			questiondata.InsertCatagory(strNewCatagory);
	                    			Toast.makeText(getApplicationContext(), "Insert level "+ strNewCatagory+ " success !", Toast.LENGTH_SHORT).show();
								} catch (Exception e) {
									Toast.makeText(getApplicationContext(), "Can not Insert level "+ strNewCatagory, Toast.LENGTH_SHORT).show();
								}
								arraylistcatagory.clear();
								cataadapter.clear();
								showLevel();
	                    		etNewCategory.setText("");
	                    		dialog.dismiss();
	                    	}
	                    	else{
	                    		etNewCategory.setText("");
	                    		Toast.makeText(getBaseContext(), "Please input value!", Toast.LENGTH_SHORT).show();
	                    	}
	                    	
	                    }
	                })
	                .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
	                    public void onClick(DialogInterface dialog, int whichButton) {
	                    	//etNewCategory.setText("");
	                        dialog.dismiss();
	                    }
	                })
	                .create();
		}
		return null;
   }//end dialog
	
	
	
    @Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub
		super.onCreateOptionsMenu(menu);
		CreateMenu(menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
		super.onOptionsItemSelected(item);
		return MenuChoice(item);
	}

	private void CreateMenu(Menu menu)
    {
    	menu.add(0, 0, 0, SETTING);
    	menu.add(0, 1, 0, LEVELMANAGE);
    }
	
   private boolean MenuChoice(MenuItem item)
   {
	switch (item.getItemId()) {
	case 0:
		Intent intentshare = new Intent(InsertQuestion.this, SettingActivity.class);
		startActivity(intentshare);
		return true;
		
	case 1:
		Intent intent = new Intent(InsertQuestion.this, ListCatagory.class);
		startActivity(intent);
		InsertQuestion.this.finish();
		return true;
	}
	return false;
	   
   }   
}
